const co = require('co');
const models = require('../models');
const logger = require('flogger').getLogger();
const Organization = models.Organization;
const Team = models.Team;
const Utility = require('../util/util').Utility;

/**
 * @param storeId
 * @param roleId
 * @returns {*|Promise}
 */
module.exports.queryTeamsDetail = function (storeId, roleId) {
  return co(function*() {
    // 根据店铺信息查找组织
    let org = yield Organization.findOne({
      where: {
        storeId: storeId
      }
    });

    if (!org) {
      throw `店铺 ${storeId} 不存在`;
    }

    // 根据组织ID和分组角色查找群组
    let condition = {
      organizationId: org.id
    };

    if (roleId) {
      condition.roleId = roleId;
    }

    logger.info('正在查询team信息', condition);
    let teams = yield Team.findAll({
      where: condition,
      include: {
        model: models.User,
        attributes: ['id', 'uid', 'nickname', 'contactNumber', 'storeName', 'storeId', 'partyGroup', 'portraitUri']
      },
      attributes: ['id', 'teamName']
    });

    // 删除中间表，合并到Users, 将user的id加密
    return teams.map(team => {
      let plainTeam = team.get({plain: true});
      logger.info('获取到team:', plainTeam);
      plainTeam.Users = plainTeam.Users.map(user => {
        user.displayName = user.TeamUser.displayName;
        user.isMaster = user.TeamUser.isMaster;
        user.id = Utility.numberToString(user.id);
        delete user.TeamUser;
        return user;
      });
      return plainTeam;
    });
  }).catch(err => {
    logger.warn('查询Team出错了', err);
    throw err;
  });
};
